import pymysql


class DBUtils:
    @staticmethod
    def __get_connect():
        connect = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                                  password="iHRM_student_2021", database="ihrm")
        return connect

    @classmethod
    def db_uid(cls, sql):
        connect = None
        cursor = None
        try:
            connect = cls.__get_connect()
            cursor = connect.cursor()
            cursor.execute(sql)
            print("影响行数", connect.affected_rows())
            # 新增的ID
            # print("新增ID",cursor.lastrowid)
            connect.commit()
        except Exception as e:
            # 操作失败事务回滚
            connect.rollback()
            print("事务回滚", e)
        finally:
            cursor.close()
            connect.close()

    @classmethod
    def db_query(cls, sql):
        connect = None
        cursor = None
        result = None
        try:
            connect = cls.__get_connect()
            cursor = connect.cursor()
            cursor.execute(sql)
            # 获取一行结果(游标会逐行向下获取数据)
            result = cursor.fetchone()
            # 获取全部结果(游标会逐行向下获取数据)
            # result = cursor.fetchall()
            # 获取结果集中的指定size行数据(游标会逐行向下获取数据)
            # result = cursor.fetchmany(3)
        except Exception as e:
            print("查询失败", e)
        finally:
            cursor.close()
            connect.close()
            return result


if __name__ == '__main__':
    DBUtils.db_uid("delete from bs_user where mobile = '18400000001';")
    # print(res)
    # for i in res:
    #     print(i)
